<template>
  <div class="cashier-container">
    <!-- 顶部工具栏 -->
    <div class="cashier-header">
      <div class="header-left">
        <h2>收银台</h2>
        <span class="cashier-info">收银员：{{ currentCashier }} | 收银台：{{ cashierStation }}</span>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="openMemberDialog">会员管理</el-button>
        <el-button @click="openPromotionDialog">促销活动</el-button>
        <el-button @click="openSettings">设置</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="cashier-main">
      <!-- 左侧：商品区域 -->
      <div class="product-section">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input
            v-model="searchKeyword"
            placeholder="扫码或输入商品名称/条码"
            size="large"
            @keyup.enter="searchProduct"
            @input="onSearchInput"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="searchProduct">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>

        <!-- 商品分类 -->
        <div class="category-tabs">
          <el-tabs v-model="activeCategory" @tab-click="onCategoryChange">
            <el-tab-pane
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :name="category.id"
            />
          </el-tabs>
        </div>

        <!-- 商品网格 -->
        <div class="product-grid">
          <div
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-item"
            @click="addToCart(product)"
          >
            <div class="product-image">
              <img :src="product.image || '/default-product.png'" :alt="product.name" />
            </div>
            <div class="product-info">
              <h4>{{ product.name }}</h4>
              <p class="product-code">{{ product.code }}</p>
              <div class="product-price">
                <span class="price">¥{{ product.price.toFixed(2) }}</span>
                <span v-if="product.stock !== -1" class="stock">库存：{{ product.stock }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：购物车和结算区域 -->
      <div class="cart-section">
        <!-- 购物车 -->
        <div class="cart-header">
          <h3>购物车</h3>
          <el-button type="danger" size="small" @click="clearCart">清空</el-button>
        </div>

        <div class="cart-items">
          <div v-if="cartItems.length === 0" class="empty-cart">
            <el-empty description="购物车为空" />
          </div>
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item"
          >
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p class="item-code">{{ item.code }}</p>
              <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
            </div>
            <div class="item-controls">
              <el-button-group>
                <el-button size="small" @click="decreaseQuantity(item)">-</el-button>
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock || 999"
                  size="small"
                  controls-position="right"
                  @change="updateQuantity(item, $event)"
                />
                <el-button size="small" @click="increaseQuantity(item)">+</el-button>
              </el-button-group>
              <el-button
                type="danger"
                size="small"
                @click="removeFromCart(item)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 优惠券 -->
        <div class="coupon-section">
          <el-input
            v-model="couponCode"
            placeholder="输入优惠券代码"
            size="small"
          >
            <template #append>
              <el-button @click="applyCoupon">使用</el-button>
            </template>
          </el-input>
        </div>

        <!-- 结算区域 -->
        <div class="checkout-section">
          <div class="total-info">
            <div class="total-line">
              <span>商品总额：</span>
              <span>¥{{ subtotal.toFixed(2) }}</span>
            </div>
            <div v-if="discountAmount > 0" class="total-line discount">
              <span>优惠金额：</span>
              <span>-¥{{ discountAmount.toFixed(2) }}</span>
            </div>
            <div class="total-line final">
              <span>应付金额：</span>
              <span class="final-amount">¥{{ finalAmount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="payment-methods">
            <h4>支付方式</h4>
            <el-radio-group v-model="paymentMethod">
              <el-radio-button label="cash">现金</el-radio-button>
              <el-radio-button label="card">银行卡</el-radio-button>
              <el-radio-button label="alipay">支付宝</el-radio-button>
              <el-radio-button label="wechat">微信</el-radio-button>
            </el-radio-group>
          </div>

          <div class="checkout-actions">
            <el-button
              type="success"
              size="large"
              :disabled="cartItems.length === 0"
              @click="processPayment"
            >
              确认结算
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 会员管理对话框 -->
    <el-dialog v-model="memberDialogVisible" title="会员管理" width="600px">
      <div class="member-search">
        <el-input
          v-model="memberSearchKeyword"
          placeholder="输入会员手机号或会员卡号"
          @keyup.enter="searchMember"
        >
          <template #append>
            <el-button @click="searchMember">查询</el-button>
          </template>
        </el-input>
      </div>

      <div v-if="currentMember" class="member-info">
        <el-card>
          <div class="member-details">
            <h4>{{ currentMember.name }}</h4>
            <p>手机号：{{ currentMember.phone }}</p>
            <p>会员卡号：{{ currentMember.cardNumber }}</p>
            <p>积分：{{ currentMember.points }}</p>
            <p>等级：{{ currentMember.level }}</p>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="memberDialogVisible = false">关闭</el-button>
        <el-button v-if="currentMember" type="primary" @click="confirmMember">确认</el-button>
      </template>
    </el-dialog>

    <!-- 促销活动对话框 -->
    <el-dialog v-model="promotionDialogVisible" title="促销活动" width="800px">
      <div class="promotion-list">
        <el-card
          v-for="promotion in availablePromotions"
          :key="promotion.id"
          class="promotion-card"
          @click="applyPromotion(promotion)"
        >
          <div class="promotion-info">
            <h4>{{ promotion.name }}</h4>
            <p>{{ promotion.description }}</p>
            <el-tag :type="promotion.type === 'discount' ? 'success' : 'warning'">
              {{ promotion.type === 'discount' ? '折扣' : '满减' }}
            </el-tag>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="promotionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付确认对话框 -->
    <el-dialog v-model="paymentDialogVisible" title="支付确认" width="400px">
      <div class="payment-confirm">
        <div class="amount-display">
          <h2>应付金额：¥{{ finalAmount.toFixed(2) }}</h2>
        </div>
        <div class="received-amount">
          <el-input-number
            v-model="receivedAmount"
            :min="finalAmount"
            placeholder="实收金额"
            size="large"
          />
        </div>
        <div v-if="receivedAmount > finalAmount" class="change-amount">
          找零：¥{{ (receivedAmount - finalAmount).toFixed(2) }}
        </div>
      </div>

      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmPayment">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 响应式数据
const currentCashier = ref('收银员001')
const cashierStation = ref('收银台001')
const searchKeyword = ref('')
const activeCategory = ref('all')
const cartItems = ref([])
const couponCode = ref('')
const discountAmount = ref(0)
const paymentMethod = ref('cash')
const memberDialogVisible = ref(false)
const memberSearchKeyword = ref('')
const currentMember = ref(null)
const promotionDialogVisible = ref(false)
const paymentDialogVisible = ref(false)
const receivedAmount = ref(0)

// 商品数据
const categories = ref([
  { id: 'all', name: '全部' },
  { id: 'electronics', name: '电子产品' },
  { id: 'clothing', name: '服装鞋帽' },
  { id: 'food', name: '食品饮料' },
  { id: 'home', name: '家居用品' }
])

const products = ref([
  {
    id: 1,
    name: 'iPhone 15',
    code: 'IP15-128',
    price: 5999,
    category: 'electronics',
    stock: 15,
    image: '/products/iphone15.jpg'
  },
  {
    id: 2,
    name: 'MacBook Air',
    code: 'MBA-M2',
    price: 8999,
    category: 'electronics',
    stock: 8,
    image: '/products/macbook.jpg'
  },
  {
    id: 3,
    name: 'Nike运动鞋',
    code: 'NIKE-001',
    price: 599,
    category: 'clothing',
    stock: 25,
    image: '/products/nike.jpg'
  },
  {
    id: 4,
    name: '可口可乐',
    code: 'COKE-330',
    price: 3.5,
    category: 'food',
    stock: 100,
    image: '/products/coke.jpg'
  },
  {
    id: 5,
    name: '保温杯',
    code: 'CUP-500',
    price: 89,
    category: 'home',
    stock: 30,
    image: '/products/cup.jpg'
  }
])

// 促销活动数据
const availablePromotions = ref([
  {
    id: 1,
    name: '满100减10',
    description: '单笔消费满100元减10元',
    type: 'discount',
    condition: { minAmount: 100 },
    discount: 10
  },
  {
    id: 2,
    name: '电子产品9折',
    description: '电子产品全场9折优惠',
    type: 'discount',
    condition: { category: 'electronics' },
    discount: 0.1
  }
])

// 计算属性
const filteredProducts = computed(() => {
  let result = products.value

  // 按分类筛选
  if (activeCategory.value !== 'all') {
    result = result.filter(p => p.category === activeCategory.value)
  }

  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(p => 
      p.name.toLowerCase().includes(keyword) ||
      p.code.toLowerCase().includes(keyword)
    )
  }

  return result
})

const subtotal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

const finalAmount = computed(() => {
  return Math.max(0, subtotal.value - discountAmount.value)
})

// 方法
const searchProduct = () => {
  if (!searchKeyword.value.trim()) return
  
  // 模拟扫码搜索
  const product = products.value.find(p => 
    p.code.toLowerCase() === searchKeyword.value.toLowerCase()
  )
  
  if (product) {
    addToCart(product)
    searchKeyword.value = ''
    ElMessage.success(`已添加 ${product.name} 到购物车`)
  } else {
    ElMessage.warning('未找到该商品')
  }
}

const onSearchInput = () => {
  // 实时搜索逻辑
}

const onCategoryChange = () => {
  // 分类切换逻辑
}

const addToCart = (product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id)
  
  if (existingItem) {
    if (product.stock !== -1 && existingItem.quantity >= product.stock) {
      ElMessage.warning('库存不足')
      return
    }
    existingItem.quantity++
  } else {
    cartItems.value.push({
      ...product,
      quantity: 1
    })
  }
  
  ElMessage.success(`已添加 ${product.name} 到购物车`)
}

const removeFromCart = (item) => {
  const index = cartItems.value.findIndex(cartItem => cartItem.id === item.id)
  if (index > -1) {
    cartItems.value.splice(index, 1)
    ElMessage.success('已从购物车移除')
  }
}

const increaseQuantity = (item) => {
  if (item.stock !== -1 && item.quantity >= item.stock) {
    ElMessage.warning('库存不足')
    return
  }
  item.quantity++
}

const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity--
  }
}

const updateQuantity = (item, quantity) => {
  if (quantity < 1) {
    removeFromCart(item)
    return
  }
  if (item.stock !== -1 && quantity > item.stock) {
    ElMessage.warning('库存不足')
    item.quantity = item.stock
    return
  }
  item.quantity = quantity
}

const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cartItems.value = []
    discountAmount.value = 0
    ElMessage.success('购物车已清空')
  })
}

const applyCoupon = () => {
  if (!couponCode.value.trim()) {
    ElMessage.warning('请输入优惠券代码')
    return
  }

  // 模拟优惠券验证
  const validCoupons = {
    'SAVE10': { discount: 10, type: 'amount' },
    'DISCOUNT20': { discount: 20, type: 'percentage' },
    'DISCOUNT10': { discount: 0.1, type: 'percentage' },
    'SAVE50': { discount: 50, type: 'amount' }
  }

  const coupon = validCoupons[couponCode.value.toUpperCase()]
  if (coupon) {
    if (coupon.type === 'amount') {
      discountAmount.value = Math.min(coupon.discount, subtotal.value)
    } else {
      discountAmount.value = subtotal.value * coupon.discount
    }
    ElMessage.success('优惠券使用成功')
    couponCode.value = ''
  } else {
    ElMessage.error('无效的优惠券代码')
  }
}

const openMemberDialog = () => {
  memberDialogVisible.value = true
  memberSearchKeyword.value = ''
  currentMember.value = null
}

const searchMember = () => {
  if (!memberSearchKeyword.value.trim()) {
    ElMessage.warning('请输入会员信息')
    return
  }

  // 模拟会员查询
  const mockMembers = [
    {
      id: 1,
      name: '张三',
      phone: '13800138000',
      cardNumber: 'M001',
      points: 1500,
      level: '金卡会员'
    },
    {
      id: 2,
      name: '李四',
      phone: '13900139000',
      cardNumber: 'M002',
      points: 800,
      level: '银卡会员'
    }
  ]

  const member = mockMembers.find(m => 
    m.phone === memberSearchKeyword.value || 
    m.cardNumber === memberSearchKeyword.value.toUpperCase()
  )

  if (member) {
    currentMember.value = member
    ElMessage.success('找到会员信息')
  } else {
    ElMessage.warning('未找到该会员')
    currentMember.value = null
  }
}

const confirmMember = () => {
  if (currentMember.value) {
    ElMessage.success(`已选择会员：${currentMember.value.name}`)
    memberDialogVisible.value = false
  }
}

const openPromotionDialog = () => {
  promotionDialogVisible.value = true
}

const applyPromotion = (promotion) => {
  if (promotion.condition.minAmount && subtotal.value < promotion.condition.minAmount) {
    ElMessage.warning(`需要满${promotion.condition.minAmount}元才能使用此优惠`)
    return
  }

  if (promotion.type === 'discount') {
    discountAmount.value = subtotal.value * promotion.discount
  } else {
    discountAmount.value = promotion.discount
  }

  ElMessage.success(`已应用促销活动：${promotion.name}`)
  promotionDialogVisible.value = false
}

const openSettings = () => {
  ElMessage.info('设置功能开发中')
}

const processPayment = () => {
  if (paymentMethod.value === 'cash') {
    receivedAmount.value = finalAmount.value
    paymentDialogVisible.value = true
  } else {
    // 其他支付方式直接确认
    confirmPayment()
  }
}

const confirmPayment = () => {
  // 生成订单
  const order = {
    id: 'SO' + Date.now(),
    items: cartItems.value,
    subtotal: subtotal.value,
    discount: discountAmount.value,
    total: finalAmount.value,
    paymentMethod: paymentMethod.value,
    cashier: currentCashier.value,
    timestamp: new Date().toISOString(),
    member: currentMember.value
  }

  // 模拟支付处理
  ElMessage.success('支付成功！')
  
  // 打印小票
  printReceipt(order)
  
  // 清空购物车
  cartItems.value = []
  discountAmount.value = 0
  currentMember.value = null
  couponCode.value = ''
  paymentDialogVisible.value = false
  
  ElMessage.success('订单已完成')
}

const printReceipt = (order) => {
  // 模拟打印小票
  console.log('打印小票：', order)
  ElMessage.info('小票已打印')
}

// 生命周期
onMounted(() => {
  // 初始化收银台
  console.log('收银台已启动')
})
</script>

<style scoped>
.cashier-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.cashier-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.cashier-info {
  color: #909399;
  font-size: 14px;
  margin-left: 16px;
}

.cashier-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.product-section {
  flex: 2;
  background: white;
  margin: 16px 0 16px 16px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.search-area {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.category-tabs {
  padding: 0 16px;
}

.product-grid {
  flex: 1;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  overflow-y: auto;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.product-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.product-image {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.product-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.product-code {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #909399;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.stock {
  font-size: 12px;
  color: #909399;
}

.cart-section {
  flex: 1;
  background: white;
  margin: 16px 16px 16px 0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.cart-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h3 {
  margin: 0;
  color: #303133;
}

.cart-items {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.empty-cart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.cart-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.item-code {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #909399;
}

.item-price {
  font-size: 14px;
  font-weight: bold;
  color: #f56c6c;
}

.item-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.coupon-section {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.checkout-section {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.total-info {
  margin-bottom: 16px;
}

.total-line {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.total-line.discount {
  color: #67c23a;
}

.total-line.final {
  font-size: 16px;
  font-weight: bold;
  border-top: 1px solid #e4e7ed;
  padding-top: 8px;
}

.final-amount {
  color: #f56c6c;
  font-size: 18px;
}

.payment-methods {
  margin-bottom: 16px;
}

.payment-methods h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
}

.checkout-actions {
  text-align: center;
}

.member-search {
  margin-bottom: 16px;
}

.member-info {
  margin-bottom: 16px;
}

.member-details h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.member-details p {
  margin: 4px 0;
  color: #606266;
}

.promotion-list {
  max-height: 400px;
  overflow-y: auto;
}

.promotion-card {
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.promotion-card:hover {
  border-color: #409eff;
}

.promotion-info h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.promotion-info p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.payment-confirm {
  text-align: center;
}

.amount-display {
  margin-bottom: 24px;
}

.amount-display h2 {
  color: #f56c6c;
  margin: 0;
}

.received-amount {
  margin-bottom: 16px;
}

.change-amount {
  font-size: 16px;
  color: #67c23a;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .cashier-main {
    flex-direction: column;
  }
  
  .product-section,
  .cart-section {
    margin: 8px;
    flex: none;
  }
  
  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>